package dao.impl;

import java.util.List;

import table.ClientTable;
import rt.AbstractDao;
import entity.Client;

public class ClientDao extends AbstractDao<ClientTable, Client> {

	public ClientDao(String rootFolderPath) {
		super(rootFolderPath);
	}

	@Override
	public void saveNew(final Client newClient) {
		final ClientTable clientTable = deserializeFromXml();

		int count = 0;

		for (Client row : clientTable.getRows()) {
			if (row.getInfoUser().getLogin()
					.equals(newClient.getInfoUser().getLogin()))
				count++;
		}

		if (count == 0) {
			//newClient.setId(getNextId());
			clientTable.getRows().add(newClient);
		}

		serializeToXml(clientTable);
	}

	@Override
	public void update(Client entity) {
		final ClientTable clientTable = deserializeFromXml();
		for (final Client row : clientTable.getRows()) {
			if (row.getInfoUser().getLogin()
					.equals(entity.getInfoUser().getLogin())) {
				row.getInfoUser().setName(entity.getInfoUser().getName());
				row.getInfoUser().setSurname(entity.getInfoUser().getSurname());
				row.setCreditCards(entity.getCreditCards());
				break;
			}
		}
		serializeToXml(clientTable);
	}

	@Override
	public Client get(final String login) {
		final ClientTable clientTable = deserializeFromXml();
		for (final Client row : clientTable.getRows()) {
			if (row.getInfoUser().getLogin().equals(login)) {
				return row;
			}
		}
		return null;
	}

	@Override
	public List<Client> getAll() {
		final ClientTable clientTable = deserializeFromXml();
		return clientTable.getRows();
	}

	@Override
	public void delete(String login) {
		final ClientTable clientTable = deserializeFromXml();
		for (final Client row : clientTable.getRows()) {
			if (row.getInfoUser().getLogin().equals(login)) {
				clientTable.getRows().remove(row);
				break;
			}
		}
		serializeToXml(clientTable);
	}

	@Override
	protected Class<ClientTable> getTableClass() {
		return ClientTable.class;
	}

}
